#include "app_router.h"
#include "app_mqtt.h"
#include "app_message.h"
#include "app_device.h"
#include "log/log.h"

static Device *device_list[MAX_DEVICE_COUNT];
static int device_count = 0;

static int app_router_recvMsg(void *ptr, int len)
{
    char buf[128];
    Message *message = app_message_initByJson(ptr, len);
    for (int i = 0; i < device_count; i++)
    {
        if (message->conn_type == device_list[i]->conn_type)
        {
            int result = app_message_toBinary(message, buf, sizeof(buf));
            app_message_free(message);
            if (result == -1)
            {
                log_error("app_router_mqttCallback: app_message_toBinary failed");
                return -1;
            }
            app_device_recvMsg(device_list[i], buf, result);
            return 0;
        }
    }

    log_warn("app_router_mqttCallback: no device found");
    app_message_free(message);
    return -1;
}

static void app_router_sendMsg(Device *device, void *ptr, int len)
{
    char buf[1024];
    Message *message = app_message_initByBinary(ptr, len);
    if (message == NULL)
    {
        log_error("app_router_deviceCallback: app_message_initByBinary failed");
        return;
    }
    int result = app_message_toJson(message, buf, sizeof(buf));
    if (result < 0)
    {
        log_error("app_router_deviceCallback: app_message_toJson failed");
        app_message_free(message);
        return;
    }
    app_mqtt_send(buf, result);
    app_message_free(message);
}

int app_router_init()
{
    if (app_mqtt_init() != 0)
    {
        log_error("app_router_init: app_mqtt_init failed");
        return -1;
    }
    app_mqtt_registerRecvCallback(app_router_recvMsg);
    return 0;
}

void app_router_close()
{
    app_mqtt_close();
    for(int i = 0; i < device_count; i++)
    {
        app_device_stop(device_list[i]);
        app_device_close(device_list[i]);
    }
}

int app_router_registerDevice(Device *device)
{
    if (device_count >= MAX_DEVICE_COUNT)
    {
        log_error("app_router_registerDevice: device count exceeds MAX_DEVICE_COUNT");
        return -1;
    }
    device_list[device_count++] = device;
    device->funcs->send_msg = app_router_sendMsg;
    app_device_start(device);

    return 0;
}